package com.cc.chioceFileListView;

import java.io.File;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;

/** 从路径加载图片的线程通过接口回调 **/
public class LoadBitmapThread extends Thread {
	
	OnBitmapLoadOkListener mOnBitmapLoadOkListener;
	String mPath;
	int width;
	Handler handler;
	Bitmap bitmap;
	
	boolean isStop = false;
	
	public LoadBitmapThread(Context activity, String path, int width, OnBitmapLoadOkListener listener){
		this.handler = new Handler(activity.getMainLooper());
		this.mPath = path;
		this.mOnBitmapLoadOkListener = listener;
		this.width = width;
	}
	
	public void kill(){
		this.isStop = false;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		if(isStop){
			return;
		}
		File file = new File(mPath);
		if(!file.exists()){
			handler.post(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					if(mOnBitmapLoadOkListener!=null)
						mOnBitmapLoadOkListener.onLoadFail();
				}
			});
			return;
		}
		if(isStop){
			return;
		}
		try {
			bitmap = BitmapOptimization.getBitmap(file.toString(), width);//BitmapFactory.decodeStream(new FileInputStream(file));
			handler.post(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					if(isStop){
						return;
					}
					if(mOnBitmapLoadOkListener!=null){
						mOnBitmapLoadOkListener.onLoadFinish(bitmap);
					}
					bitmap = null;
				}
			});
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			new File(mPath).delete();
			handler.post(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					if(isStop){
						return;
					}
					if(mOnBitmapLoadOkListener!=null)
						mOnBitmapLoadOkListener.onLoadFail();
				}
			});
		}
	}
}
